<?php

namespace app\user\model;

use app\common\model\TimeModel;


class UserPraise extends TimeModel
{
    public function setIp2longAttr($value){
        return ip2long($value);
    }

    public function getIp2longAttr($value){
        return long2ip($value);
    }
    public static function checkIsPraised($objectType, $objectId, $userId = 0, $ip = '')
    {
        $hasPraised = 0;
        if ($userId) {
            $map['user_id'] = $userId;
        } elseif ($ip) {
            $map['ip2long'] = ip2long($ip);
        } else {
            return false;
        }
        $map['subject'] = $objectType;
        $map['subject_id'] = $objectId;
        $find = (new static())->where($map)->find();
        if ($find) $hasPraised = 1;
        return $hasPraised;
    }

    public static function setIncPraise($objectType, $objectId, $userId = 0, $badGood = 1)
    {
        if ($userId) {
            $data['user_id'] = $userId;
        }

            $data['ip2long'] = request()->ip();

        $data['subject'] = $objectType;
        $data['subject_id'] = $objectId;

        $model = '\\app\\common\\model\\'.ucfirst(strtolower($objectType));
        $field='praise_num';
        $id='id';
        if($objectType=='COMMENT'){
            $field=$badGood.'_num';
        }
        $object = (new $model())->where($id, $objectId)->find();
        if ($object) {
            $object->$field += 1;
            $object->save();
            (new static())->create($data);
        }
        return true;
    }
}